package com.lkd.handler;

import com.google.common.collect.Lists;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
@Slf4j
public class SupplyReplenishment implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) {
        try {
            //解析协议内容
            SupplyContract supplyChannel = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
            if (supplyChannel == null) return;
            //找出被指派的人
            VmVO vmInfo = vmService.getVMInfo(supplyChannel.getInnerCode());
            if (vmInfo == null) return;
            int user = taskService.getLeastUser(vmInfo.getRegionId(), false);
            if (user == 0) return;
            //创建补货工单
            TaskViewModel model = new TaskViewModel();
            //任务执行人
            model.setUserId(user);
            //工单类型
            model.setCreateType(0);
            //售货机编号
            model.setInnerCode(supplyChannel.getInnerCode());
            //用户创建人id
            model.setAssignorId(0);
            //工单类型
            model.setProductType(VMSystem.TASK_TYPE_SUPPLY);
            model.setDesc("自动补货工单");

            model.setDetails(supplyChannel.getSupplyData().stream().map(c -> {
                TaskDetailsViewModel viewModel = new TaskDetailsViewModel();
                //货道编号
                viewModel.setChannelCode(c.getChannelId());
                //期望补货数量
                viewModel.setExpectCapacity(c.getCapacity());
                //商品Id
                viewModel.setSkuId(c.getSkuId());
                //商品名称
                viewModel.setSkuName(c.getSkuName());
                //商品图片
                viewModel.setSkuImage(c.getSkuImage());
                //返回所有数据
                return viewModel;
            }).collect(Collectors.toList()));

            taskService.createTask(model);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("创建自动补货工单失败" + e.getMessage());
        }
    }
}
